<template>
  <div class="app-container warp_auto">
    <el-card>
      <el-button type="primary" @click="displayDrawer">添加计划</el-button>
      <el-select
        v-model="disabled"
        class="input"
        clearable
        placeholder="请选择"
        filterable
        style="margin: 0 20px;"
      >
        <el-option
          v-for="item in list_disabled"
          :key="item.id"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" @click="handleCurrentChange(1)">查询</el-button>
    </el-card>
    <el-card>
      <el-table
        :data="taskData"
        stripe style="width: 100%"
        :header-cell-style=" { background:'#d2e0f9', color: '#606266' }"
        ref="multipleTable"
      >
        <el-table-column type="index" label="序号" fixed/>
        <el-table-column label="id" align="center" prop="id" v-if="false"/>
        <el-table-column label="任务名称" align="center" prop="name"/>
        <el-table-column label="任务频次" align="center">
          <template slot-scope="scope">
            {{ scope.row.frequency }}
            {{ scope.row.frequencyUnit === 0 ? '小时' : (scope.row.frequencyUnit === 1 ? '天' : '月') }} /次
          </template>
        </el-table-column>
        <el-table-column label="剩余次数" align="center" prop="executeNums">
          <template slot-scope="scope">
            {{ scope.row.adviceType === 0 ? scope.row.executeNums : "" }}
          </template>
        </el-table-column>
        <el-table-column label="任务类型" align="center" prop="adviceType">
          <template slot-scope="scope">
            {{ scope.row.adviceType === 1 ? '长医嘱' : scope.row.adviceType === 0 ? '临时医嘱' : "" }}
          </template>
        </el-table-column>
        <el-table-column label="任务描述" align="center" prop="autoDesc"/>
        <el-table-column label="自动执行" align="center" prop="autoStatus">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.autoStatus === 1" type="success">是</el-tag>
            <el-tag v-else-if="scope.row.autoStatus === 0" type="danger">否</el-tag>
            <el-tag v-else type="warning">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="第一次执行时间" align="center" prop="beginTime"/>
        <el-table-column label="最后执行时间" align="center" prop="lastExecuteTime"/>
        <el-table-column label="状态" align="center" prop="disabled">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.disabled === 1" type="success">启用</el-tag>
            <el-tag v-else-if="scope.row.disabled === 0" type="danger">禁用</el-tag>
            <el-tag v-else type="warning">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="editDisplayDrawer(scope.row)">编辑</el-button>
            <el-button :type="scope.row.disabled === 1 ? 'danger' : 'primary'" size="mini" @click="stopTask(scope.row)">
              {{ scope.row.disabled === 1 ? '停用' : '启用' }}
            </el-button>
            <el-button type="danger" size="mini" @click="deleteTask(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="paging">
        <el-pagination
          :current-page="start"
          :page-size="pageSize"
          :page-sizes="pageSizes"
          :pager-count="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-drawer
      :title=drawerTitle
      :with-header="true"
      :visible.sync="drawer"
      :before-close="handleClose"
      size="50%"
    >
      <div class="drawer_content">
        <div class="drawer_form">
          <el-form :model="taskFrom" :rules="rules" label-width="125px" ref="ruleFormRef">
            <el-form-item label="任务名称" prop="name" required>
              <el-input v-model="taskFrom.name" placeholder="请输入任务名称"></el-input>
            </el-form-item>
            <el-form-item label="任务频次">
              <el-input-number v-model="taskFrom.frequency" :min="1" :max="100"
                               placeholder="请输入任务频次"></el-input-number>
              <el-select clearable v-model="taskFrom.frequencyUnit" placeholder="请选择单位">
                <el-option :key="0" label="小时" :value="0"></el-option>
                <el-option :key="1" label="天" :value="1"></el-option>
                <el-option :key="2" label="月" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="任务类型">
              <el-select clearable v-model="taskFrom.adviceType" placeholder="请选择类型" @change="toggleAdviceType">
                <el-option :key="1" label="长医嘱" :value="1"></el-option>
                <el-option :key="0" label="临时医嘱" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="执行次数" v-if="taskFrom.adviceType === 0">
              <el-input-number v-model="taskFrom.executeNums" :min="1" :max="100"
                               placeholder="请输入执行次数"></el-input-number>
            </el-form-item>
            <el-form-item label="任务描述">
              <el-input v-model="taskFrom.autoDesc" placeholder="请输入任务描述"></el-input>
            </el-form-item>
            <el-form-item label="自动执行">
              <el-radio-group v-model="taskFrom.autoStatus">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="第一次执行时间">
              <el-date-picker
                v-model="taskFrom.beginTime"
                placeholder="选择时间"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                format="yyyy-MM-dd HH:mm"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="taskFrom.disabled">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="关联医嘱">
              <el-select clearable v-model="taskFrom.adviceIdList" multiple placeholder="请选择关联任务">
                <el-option v-for="item in adviceData" :key="item.id" :label="item.orderName"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item :style="{
                  position: 'absolute',
                  right: 0,
                  bottom: 0,
                  width: '100%',
                  borderTop: '1px solid #e9e9e9',
                  padding: '10px 16px',
                  background: '#fff',
                  textAlign: 'right',
                  zIndex: 1,
                }">
              <el-button @click="handleClose">取消</el-button>
              <el-button type="primary" @click="submit('ruleFormRef')">提交</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import {getList, add, update, remove, adviceList, disabled} from "@/api/Ztask"
import {dateUtils} from "@/utils/dateUtils";

export default {
  data() {
    return {
      list_disabled: [
        {
          label: '启用',
          value: 1
        },
        // {
        //   label: '禁用',
        //   value: 0
        // },
        {
          label: '全部',
          value: -1
        }
      ],
      disabled: 1,
      ruleFormRef: {
        name: '',
      },
      rules: {
        name: [
          {required: true, message: '请输入任务名称', trigger: 'change'}
        ],
      },
      start: 1, // 默认显示第几页
      pageSize: 10, // 默认每页显示的条数（可修改）
      pageSizes: [10, 20, 30, 40], // 个数选择器（可修改）
      totalCount: 0, // 总条数，根据接口获取数据长度(注意：这里不能为空)
      patientId: "",//患者id
      data: {},//患者信息
      drawerTitle: "", // 抽屉标题
      taskFrom: {
        id: "",
        name: "",
        patientId: "",//患者id
        adviceIdList: [],
        adviceType: "",
        frequency: 1,
        frequencyUnit: 0,
        executeNums: 1,
        autoDesc: "",
        autoStatus: 1,
        beginTime: "",
        lastExecuteTime: "",
        disabled: 1,
      },
      drawer: false,
      taskData: [],//计划列表
      adviceData: [],//病人医嘱列表
    };
  },
  computed: {
    getData() {
      return this.$store.state.user.severFall;
    },
  },
  watch: {
    getData() {
      this.initData();
    },
  },
  mounted() {
    this.initData();
  },
  methods: {
    dateUtils,
    //初始化方法
    initData() {
      this.enterStartTime = dateUtils(1, null);
      this.data = this.$store.state.user.severFall;
      if (
        typeof this.data.patient_id == "string" &&
        this.data.patient_id.length > 0
      ) {
        this.patientId = this.data.patient_id;
        this.queryData(this.pageSize, this.start);
      } else {
        this.$message({
          message: "请先选择病人",
          type: "warning",
        });
      }
    },
    toggleAdviceType(){
      if(this.taskFrom.adviceType !== ""){
        this.queryAdviceData(this.taskFrom.adviceType)
      }
    },
    displayDrawer() {
      this.drawer = true;
      this.drawerTitle = "添加计划";
      // this.queryAdviceData()
    },
    editDisplayDrawer(row) {
      console.log(row);
      this.drawer = true;
      this.drawerTitle = "编辑计划";
      this.taskFrom = {
        id: row.id,
        name: row.name,
        adviceType: row.adviceType,
        frequency: row.frequency,
        frequencyUnit: row.frequencyUnit,
        executeNums: row.executeNums,
        autoDesc: row.autoDesc,
        autoStatus: row.autoStatus,
        beginTime: row.beginTime,
        disabled: row.disabled,
        adviceIdList: row.adviceIdList
      };
      this.queryAdviceData(this.taskFrom.adviceType)
    },
    stopTask(row) {
      console.log("禁用", row);
      disabled(row.id, row.disabled).then((res) => {
        if (row.disabled === 1) {
          this.$message({
            type: "success",
            message: "禁用成功",
          });
        } else if (row.disabled === 0) {
          this.$message({
            type: "success",
            message: "启用成功",
          });
        }
        this.queryData(this.pageSize, this.start);
      })
    },
    deleteTask(row) {
      this.$confirm('此操作将删除该任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        remove(row.id).then((res) => {
          this.queryData(this.pageSize, this.start);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch((err) => {
          this.$message({
            type: 'error',
            message: '删除失败!'
          });
        });
      }).catch(() => {
        this.queryData(this.pageSize, this.start);
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    queryData(pageSize, start) {
      if (
        typeof this.data.patient_id == "string" &&
        this.data.patient_id.length > 0
      ) {
        let data = {}
        if (this.disabled === -1) {
          data = {
            patientId: this.patientId,
            pageSize: pageSize,
            start: start,
          }
        } else {
          data = {
            patientId: this.patientId,
            pageSize: pageSize,
            start: start,
            disabled: this.disabled
          }
        }
        getList(data).then((res) => {
          this.taskData = res.data;
          this.totalCount = res.totalCount;
          console.log(this.taskData)
        });
        // console.log(this.formatDate(this.taskData[0].createTime));
      } else {
        this.$message({message: "请先选择病人", type: "warning"});
      }

    },
    queryAdviceData(adviceType) {
      adviceList(this.patientId, adviceType).then((res) => {
        console.log(res)
        this.adviceData = res.data;
      })
    },
    handleClose() {
      this.drawer = false;
      this.resetTaskForm();
    },
    resetTaskForm() {
      this.taskFrom = Object.assign({}, this.$options.data().taskFrom);
      console.log(this.taskFrom)
    },
    submit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.taskFrom.id) {
            await update(this.taskFrom).then((res) => {
              this.$message({
                message: "提交成功",
                type: "success",
              });
            }).catch((err) => {
              this.drawer = false;
              this.resetTaskForm();
            });
          } else {
            this.taskFrom.patientId = this.data.patient_id;
            await add(this.taskFrom).then((res) => {
              this.$message({
                message: "提交成功",
                type: "success",
              });
            }).catch((err) => {
              this.drawer = false;
              this.resetTaskForm();
            });
          }
          this.queryData(this.pageSize, 1);
          this.drawer = false;
          this.resetTaskForm();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 每页显示的条数
    handleSizeChange(val) {
      // 改变每页显示的条数
      this.pageSize = val;
      // 点击每页显示的条数时，显示第一页
      this.queryData(val, 1);
      // 注意：在改变每页显示的条数时，要将页码显示到第一页
      this.start = 1;
    },
    // 显示第几页
    handleCurrentChange(val) {
      // 改变默认的页数
      this.start = val;
      // 切换页码时，要获取每页显示的条数
      this.queryData(this.pageSize, (this.start = val));
    },
    formatDate(dateObject) {
      if (!dateObject) return '';

      const year = dateObject.year;
      const month = dateObject.monthValue.toString().padStart(2, '0');
      const day = dateObject.dayOfMonth.toString().padStart(2, '0');
      const hour = dateObject.hour.toString().padStart(2, '0');
      const minute = dateObject.minute.toString().padStart(2, '0');
      const second = dateObject.second.toString().padStart(2, '0');

      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
  },
};


</script>

<style scoped lang="scss">

</style>
